package com.hope.androidproject.fragment;

import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.hope.androidproject.R;
import com.hope.androidproject.adapter.NewsListAdapter;
import com.hope.androidproject.bean.News;
import com.hope.androidproject.listener.HttpCallBackListener;
import com.hope.androidproject.utils.NetUtil;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import static com.hope.androidproject.utils.FinalValue.*;

public class NewsFragment extends Fragment implements SwipeRefreshLayout.OnRefreshListener {

    private View mView;
    private ListView mListView;
    private List<News> newsData;    //数据源
    private TextView mTitle;
    private NewsListAdapter adapter;
    private ProgressBar mProgressBar;
    private TextView mErrorInfo;
    private SwipeRefreshLayout mRefreshLayout;  //下拉刷新控件
    private static final int SET_ADAPTER = 0x01;
    private static final int ERROR_INFO_VISIBLE = 0x02;
    private static final int PROGRESS_VISIBLE = 0x03;
    private static final int PROGRESS_GONE = 0x04;


    private Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SET_ADAPTER:
                    setNewsAdapter();
                    break;
                case ERROR_INFO_VISIBLE:
                    mErrorInfo.setVisibility(View.VISIBLE);
                    break;
                case PROGRESS_VISIBLE:
                    mProgressBar.setVisibility(View.VISIBLE);
                    break;
                case PROGRESS_GONE:
                    mProgressBar.setVisibility(View.GONE);
                    break;
            }
        }
    };

    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mView = View.inflate(getActivity(), R.layout.fragment_news, null);
        return mView;
    }

    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initViews();
        initData();
    }

    /**
     * 初始化数据
     */
    private void initData() {
        newsData = new ArrayList<>();
        mProgressBar.setVisibility(View.VISIBLE);
        //TODO 获取网络的数据
        String path = SERVER_IP + PROJECT_INFO + GET_UPDATE_NEWS;
        //第一次请求如果没有缓存Id为0
        String postData = "newsId=0";
        NetUtil.sendRequest(path, POST, postData, new HttpCallBackListener() {
            public void onFinish(String response) {
                List<News> data = parseJsonStrToList(response);
                newsData.addAll(data);
                if (newsData.size() > 0) {
                    handler.sendEmptyMessage(SET_ADAPTER);
                } else {
                   handler.sendEmptyMessage(ERROR_INFO_VISIBLE);
                }
                handler.sendEmptyMessage(PROGRESS_GONE);
            }
            public void onError(Exception e) {
                handler.sendEmptyMessage(ERROR_INFO_VISIBLE);
                handler.sendEmptyMessage(PROGRESS_GONE);
            }
        });
    }

    private List<News> parseJsonStrToList(String response) {
        List<News> newsList = new ArrayList<>();
        try {
            JSONObject jsonObject = new JSONObject(response);
            //获取JSONArr
            JSONArray jsonArray = jsonObject.getJSONArray("newsList");
            //将JSonArr  装换成List集合
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject newsObj = (JSONObject) jsonArray.get(i);
                News news = new News();
                news.setNewsId(newsObj.getInt("newsId"));
                news.setNewsTiele(newsObj.getString("newsTitle"));
                news.setNewsDetail(newsObj.getString("newsDetail"));
                news.setNewsInfo(newsObj.getString("newsInfo"));
                news.setNewsImagePath(newsObj.getString("imagePath"));
                newsList.add(news);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return newsList;
    }

    private void setNewsAdapter() {
        //获取网络数据
        adapter = new NewsListAdapter(newsData, getActivity());
        mListView.setAdapter(adapter);
    }

    //初始化View
    private void initViews() {
        mListView = (ListView) mView.findViewById(R.id.news_list);
        mTitle = (TextView) mView.findViewById(R.id.title_info);
        mTitle.setText("新闻");
        mProgressBar = (ProgressBar) mView.findViewById(R.id.progress);
        mErrorInfo = (TextView) mView.findViewById(R.id.error_info);
        mRefreshLayout = (SwipeRefreshLayout) mView.findViewById(R.id.refresh_layout);
        //设置下拉刷新监听
        mRefreshLayout.setOnRefreshListener(this);
    }

    @Override
    public void onRefresh() {
        //TODO 触发下拉刷新
//        getNewsDataInfo();
    }

    public void getNewsDataInfo() {
        //TODO 获取网络的数据
        String path = SERVER_IP + PROJECT_INFO + GET_UPDATE_NEWS;
        //将列表第一条信息的Id发送到服务器
        String postData = "";
        int newsId = newsData.size() > 0 ? newsData.get(0).getNewsId() : 0;
        postData = "newsId=" + newsId;

        NetUtil.sendRequest(path, POST, postData, new HttpCallBackListener() {
            public void onFinish(String response) {
                List<News> data = parseJsonStrToList(response);
                //添加到列表顶部
                newsData.addAll(0, data);
                if (newsData.size() > 0) {
                    //刷新数据
                    adapter.notifyDataSetChanged();
                } else {
                    mErrorInfo.setVisibility(View.VISIBLE);
                }
                mProgressBar.setVisibility(View.GONE);
            }

            public void onError(Exception e) {
                mErrorInfo.setVisibility(View.VISIBLE);
                mProgressBar.setVisibility(View.GONE);
            }
        });
    }
}